<%@ page import="com.google.appengine.api.blobstore.BlobstoreServiceFactory" %>
<%@ page import="com.google.appengine.api.blobstore.BlobstoreService" %>
<%@ page import="com.google.appengine.api.users.User" %>
<%@ page import="com.google.appengine.api.users.UserService" %>
<%@ page import="com.google.appengine.api.users.UserServiceFactory" %>
<%@ page import="com.google.appengine.api.datastore.DatastoreService" %>
<%@ page import="com.google.appengine.api.datastore.DatastoreServiceFactory" %>
<%@ page import="com.google.appengine.api.datastore.Entity" %>
<%@ page import="com.MediaVaultTest.UserStore" %>
<%@ page import="com.MediaVaultTest.Media" %>
<%@ page import="com.google.appengine.api.datastore.Key" %>
<%@ page import="com.google.appengine.api.datastore.KeyFactory" %>
<%@ page import="com.google.appengine.api.datastore.PreparedQuery" %>
<%@ page import="com.google.appengine.api.datastore.Query" %>
<%@ page import="javax.jdo.JDOHelper" %>
<%@ page import="javax.jdo.PersistenceManager" %>
<%@ page import="javax.jdo.PersistenceManagerFactory" %>
<%@ page import="com.MediaVaultTest.PMF" %>
<%@ page import="javax.jdo.JDOObjectNotFoundException" %>
<%@ page import="java.util.LinkedList" %>
<%@ page import="com.MediaVaultTest.Format" %>
<%@ page import="com.MediaVaultTest.Sort" %>
<%@ page import="com.MediaVaultTest.QuotaLogic" %>
<%@ page import="com.MediaVaultTest.GetAdds" %>

<%
    BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
	GetAdds getAdds = new GetAdds();

%>

<!DOCTYPE HTML>
<html>

<head>
  <title>QUT Media Vault</title>
  <meta name="description" content="website description" />
  <meta name="keywords" content="website keywords, website keywords" />
  <meta http-equiv="content-type" content="text/html; charset=windows-1252" />
  <link rel="stylesheet" type="text/css" href="style/style.css" />
  <script type="text/javascript" src="script.js">  
  </script> 
</head>

<body>
  <%
  	//Setup user service and data store
	 UserService userService = UserServiceFactory.getUserService();
	 User user = userService.getCurrentUser();
	 
	 //If user logged in
	 if (user != null) {
		 DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		 PersistenceManager pm = PMF.get().getPersistenceManager();
		 
		 //Check if user system
		 String email =  user.getEmail();
		 
		 UserStore userStore = null;
		 Key key = KeyFactory.createKey(UserStore.class.getSimpleName(), email);
		 try { 
			 userStore = pm.getObjectById(UserStore.class, key);
			 LinkedList<Media> listOfMedia = userStore.getMedia();
		 } catch (JDOObjectNotFoundException e) {
			 userStore = null;
		 }
		 
		
		 //if not create them
		 if(userStore==null){
			 int up = 0;
			 int down = 0;
			 int store = 0;
			 userStore = new UserStore(email, up, down, store);
			 //userStore = new UserStore();
			 userStore.setKey(key);
			 
			 try {
				 pm.makePersistent(userStore);
			 } finally {
				 
			 }
		} else {
			
		}
	
  %>
  <div id="main">
    <div id="header">
      <div id="logo">
        <div id="logo_text">
          <!-- class="logo_colour", allows you to change the colour of the text -->
          <h1><a href="/">Media Vault<span class="logo_colour">QUT</span></a></h1>
          <h2>Media Centre. Currently in Alpha</h2>
        </div>
        <div id="ads_top">
			<%=
	        	getAdds.getTopBanner()
	        %>
        </div>
      </div>
      <div id="menubar">
        <ul id="menu">
          <!-- put class="selected" in the li tag for the selected page - to highlight which page you're on -->
          <li><a href="index.jsp">General</a></li>
		  <li><a href="photos.jsp">Photos</a></li>
          <li  class="selected"><a href="music.jsp">Music</a></li>
          <li><a href="movies.jsp">Movies</a></li>
          <li><a href="tv_shows.jsp">TV Shows</a></li>
		  <%if (userService.isUserAdmin()) {%>
          
		  <li><a href="adminPanel.jsp">Admin Panel</a></li>
		  <%} %>
		  <li><a href="userPanel.jsp">User Panel</a></li>
		  <li><a href="<%= userService.createLogoutURL(request.getRequestURI()) %>">Sign Out</a></li>
        </ul>
      </div>
    </div>
    <div id="site_content">
      <div class="left_sidebar">
      	  <h1>Quota Remaining</h1>
	    <table>
	      <% QuotaLogic quotaLogic = new QuotaLogic(); %>
    <tr><td>Upload</td><td><%= quotaLogic.getMBUploadRemaining(userStore) %>MB</td></tr>
    <tr><td>Download</td><td><%= quotaLogic.getMBDownloadRemaining(userStore) %>MB</td></tr>
    <tr><td>Storage</td><td><%= quotaLogic.getMBStoreRemaining(userStore) %>MB</td></tr>
	    </table>
      </div>
      
      <div class="sidebar">
      	<h1>Search</h1>
        <form method="post" action="#">
        <p>
          <input class="search" type="text" name="search_field" value="" />
          <input name="search" type="image" style="border: 0; margin: 0 0 -5px 0;" src="style/search.png" alt="Search" title="Search" />
          <select name="Field">
          <option>Title</option>
          <option>Album</option>
          <option>Artist</option>
          <option>Genre</option>
          <option>Language</option>
        </select>
        </p>
      </form>
       <div id="ads_left">
	        <%=
	        	getAdds.getRightBanner()
	        %>
        </div>
        
      </div>
      <div id="content">
        <h1>Music</h1>
			<h3>Files in System</h3>
		        <form method="post" action="#"><p>
		        <select name="displayType" onchange="refreshTable()">
		          <option>Details</option>
		          <option>Thumbnails</option>
		        </select>
		        <button onSubmit="refreshTable()">Submit</button>
		   <%	String displayType;
		        if (request.getParameter("displayType") == null) 
		        	displayType = "Details";
		        else 
		        	displayType = request.getParameter("displayType");
		        
		        String field = request.getParameter("field");
		        String order = request.getParameter("ord");
	            
		        if(field==null||order==null){
		        	field="";
		        	order="";
		        }
		        String newOrder = "asc";
	            
	            String stringKey = request.getParameter("key");
	            String image = "style/link.png";
	            //if the user choose to display the thumbnails
		        if(displayType.equals("Thumbnails")) {
		        	%> <table class="itemsTable" width="520px"><tr>	<%
				} else { 
					%> <table width="520px"><tr> <%
			        if(order.equals("asc")){
			        	newOrder = "dsc";
			        } else if(order.equals("dsc")){
			        	newOrder = "asc";
			        }
			         LinkedList<String> menu = new LinkedList<String>();
			        menu.add("Title");
			        menu.add("Size");
			        menu.add("Album");
			        menu.add("Artist");
			        menu.add("Genre");
			        menu.add("Rating");
			        menu.add("Language");
			        for(int i = 0; i < menu.size(); i++){
			        	if(field.equals(menu.get(i))){
				        	%>
				        	<td><a href="/music.jsp?field=<%=menu.get(i)%>&ord=<%= newOrder %>"><%=menu.get(i)%><img src="style/<%= order %>.png" width="16px" height"16px" /></a></td>
				        	<%
				        } else {
				        	%>
				        	<td><a href="/music.jsp?field=<%=menu.get(i)%>&ord=asc"><%=menu.get(i)%></a></td>
				        	<%
				        }
			        }
		       	%>
		        <td>Download</td></tr>
		        <% }
		        LinkedList<Media> tempList = userStore.getMedia();
		        Sort sort = new Sort(tempList);
		        String value = request.getParameter("search_field");
		        String onField = request.getParameter("Field");
		        if(value!=null&&onField!=null){
		        	%> <h2> Searching by <%= onField %> </h2> <%
		        	tempList = sort.search(onField, value);
		        }
		        if(field!=""&&order!=""){
		        	sort = new Sort(tempList);
		        	tempList = sort.sortBy(field, order);
		        }
		        sort = new Sort(tempList);
		        tempList = sort.getMediaOfType("Music");;
		        int numMediaFiles = tempList.size();
		        if(numMediaFiles==0){
		        	%> <h2>No files, of this type, found for current user</h2> <%
		        } else {
		        	//Display all files for user
			        int current = 0;
			        while(current < numMediaFiles) { 
			        	Media media = tempList.get(current); 
			        	Format format = media.getFirstFormat(); 
			        	if(displayType.equals("Thumbnails")) {
			        		String temp = media.getCoverForTrans();
			            	if(temp!=""){
			            		image = "/getThumbnail?key="+temp;
			            	} else
			            		image = "style/link.png";
			            	if (current == 0)
			            		%> <tr class="thumbnailTable"><td width="170px"> <%
			            	else if ((current % 3)==0) {
			            		%> </tr><tr class="thumbnailTable"><td >  <%
			            	} 
			            	else {
			            		%> <td > <%
			            	} %>
			        		<a href='/viewInfo.jsp?key=<%= media.getKeyForTrans()  %>'>
			        		<img src="<%=image %>" width="96px" height="96px"><Br>
					        <%= media.getTitle() %>
					        </a></td>
					        <% if ((current == numMediaFiles - 1) && (numMediaFiles % 3 != 0)) {
					        	int count = numMediaFiles / 3;
					        	count = (count + 1) * 3 - numMediaFiles;
			            		for (/*int count = 3 - current % 3*/; count > 0; count--) 
			            			 %> <td ></td> <%
			            	}
			        	} else { %>
			        	<tr>
			        	<td><a href='/viewInfo.jsp?key=<%= media.getKeyForTrans()  %>'>
			        	<%= media.getTitle() %>
			        	</a></td>
			        	<td><%=format.getSize()%></td>
			        	<td><%=media.getAlbum()%></td>
			        	<td><%=media.getArtist()%></td>
			        	<td><%=media.getGenre()%></td>
			        	<td><%=media.getRating()%></td>
			        	<td><%=media.getLanguage()%></td>
			        	<td><a href='/serve?key=<%= format.getKeyForTrans()  %>'>
			        	Download</a></td></tr>
			        	<% } 
			        		current++; %>
		       <% }} %>
			</table></form>
      </div>
    </div>
    <div id="footer">
      <p><a href="/">Home</a> | <a href="/">LOL Cats</a> | <a href="/">Contact Us</a></p>
      <p>Copyright &copy; IT CROWD | <a href="http://validator.w3.org/check?uri=referer">HTML5</a> | <a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a> | <a href="http://www.html5webtemplates.co.uk">design from HTML5webtemplates.co.uk</a></p>
    </div>
  </div>
  <%
  	pm.close();
    } else { 
  %>
        <p>Hello!
		<a href="<%= userService.createLoginURL(request.getRequestURI()) %>">Sign in</a>
		to access media vault.</p>
  <% } %>
</body>
</html>
